package com.lims.utils;


import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author limaosheng
 * @create 2022-05-10 11:14
 * @desc
 */
public class DbUtil {

    public static Connection getConn() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("", "","");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static Map<String, String> getOne(String sql,Connection conn) {
        Map<String, String> map = new HashMap<>();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            if (rs.next()) {
                for (int i = 1; i <= columnCount; i++) {
                    map.put(md.getColumnName(i), rs.getString(i));
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConn(conn);
        }
        return map;
    }

    public static List<Map<String, Object>> getList(String sql,Connection conn) {
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            while (rs.next()) {
                Map<String, Object> rowData = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(md.getColumnName(i), rs.getObject(i));
                }
                list.add(rowData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConn(conn);
        }
        return list;
    }

    public static void closeConn(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
